import 'package:get/get.dart';
import 'dart:math';
import 'shop_model.dart';

class ShopController extends GetxController {
  List<ShopModel> _classList = [];
  List get classList => _classList;
  // 昨天到时出错的原因在于这里
  void request() async {
    _classList = [];
    // 模拟网络请求获取数据
    await Future.delayed(Duration(milliseconds: 1000), () {
      for (var i = 0; i < 10; i++) {
        _classList.add(new ShopModel(i, "分类 $i"));
      }
      update();
    });
  }

  Map<int, List<GoodsModel>> map = Map();
  List<GoodsModel> _currentList = [];
  List get currentList => _currentList;
  void requstShopGoodsList(ShopModel element) {
    // 保存商品数据
    List<GoodsModel> goodsList = map[element.id];
    if (goodsList == null || goodsList.length == 0) {
      goodsList = [];
      for (int i = 0; i < 100; i++) {
        GoodsModel goods = GoodsModel();
        goods.id = i + element.id + (Random().nextInt(100));
        goods.title = "超级小水果 ${element.title}";
        goodsList.add(goods);
      }
      map[element.id] = goodsList;
    }
    _currentList = goodsList;
    //  更新
    update(["${element.id}"]);
  }

  // 定义购物车
  List<int> _cardList = [];
  List<int> get cardList => _cardList;
  void addCard(GoodsModel goods) {
    if (!_cardList.contains(goods.id)) {
      _cardList.add(goods.id);
    } else {
      _cardList.remove(goods.id);
    }
    update(['card']);
  }
}
